# -*- coding: utf-8 -*-
'''Created on 2012-7-14 @author: yemeihua'''
import smtplib,email,traceback,mimetypes,base64
from email.mime.text import MIMEText 
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart 
from email.mime.application import MIMEApplication 
from email import encoders

class Mail:
    def __init__(self,smtp,user,password,port=25):
        self.smtp = smtp
        self.user = user
        self.password = password
        self.port = port
        
    def login(self):
        self.server = smtplib.SMTP(self.smtp,self.port)
        self.server.ehlo()
        smtp_userid64 = base64.encodestring(self.user)
        self.server.docmd("auth", "login " + smtp_userid64[:-1])
        smtp_pass64 = base64.encodestring(self.password)
        self.server.docmd(smtp_pass64[:-1])  
        
    def close(self):
        self.server.quit()
        
    def send(self,to,subject,content):
        '''发送纯文本邮件'''
        result = False
        msg = MIMEMultipart()
        msg['Mime-Version']='1.0'  
        msg['From']    = self.user
        msg['To']      = to 
        msg['Subject'] = subject
        msg['Date']    = email.Utils.formatdate(localtime=True)
        msg.attach(MIMEText(content,'plain','utf-8'))
        try:      
            self.login()
            self.server.sendmail(self.user,to,msg.as_string())
            result = True
            self.close()
        except Exception,ex:  
            print Exception,ex
        finally:    
            return result
    
    def sendHTMLEmail(self,to,subject,html,img_paths=[]):
        '''发送html邮件'''
        result = False
        try:
            msg = MIMEMultipart('ralated')
            msg['Subject'] = subject  
            msg['From'] = self.user  
            msg['To'] = to  
            msg.preamble = 'This is a multi-part message in MIME format.' 
            msgAlternative = MIMEMultipart('alternative')  
            msgText = MIMEText(html, 'html', 'utf-8') 
            msg.attach(msgAlternative) 
            msgAlternative.attach(msgText)
            i=0
            for path in img_paths:
                fp = open(path,'rb')  
                msgImage = MIMEImage(fp.read())  
                fp.close()  
                msgImage.add_header('Content-ID', '<image%d>' % i)  
                msg.attach(msgImage)
                i = i+1
            self.login()
            self.server.sendmail(self.user, to, msg.as_string())
            result = True
            self.close()
        except Exception,ex:  
            print Exception,ex
        finally:
            return result
        
    def sendMultiMail(self,to,subject,html,file_paths=[],img_paths=[]):
        '''发送带附件的邮件'''
        result = False
        try:
            msg = MIMEMultipart('ralated')
            msg['Subject'] = subject  
            msg['From'] = self.user  
            msg['To'] = to  
            msg.preamble = 'This is a multi-part message in MIME format.' 
            msgAlternative = MIMEMultipart('alternative')  
            msg.attach(msgAlternative)
            
            #设定HTML信息  
            msgText = MIMEText(html, 'html', 'utf-8')  
            msgAlternative.attach(msgText)
            
            #设定内置图片信息  
            i=0
            for path in img_paths:
                fp = open(path, 'rb+')  
                msgImage = MIMEImage(fp.read())  
                fp.close()  
                msgImage.add_header('Content-ID', '<image%d>' % i )  
                msg.attach(msgImage)
                i=i+1
    
            #构造附件
            for filepath in file_paths:
                filepath = u'constant.py'
                ctype, encoding = mimetypes.guess_type(filepath)
                if ctype is None or encoding is not None:
                    ctype = 'application/octet-stream'
                maintype, subtype = ctype.split('/', 1)
                if maintype == 'text':
                    fp = open(filepath)
                    msgFile = MIMEText(fp.read(), _subtype=subtype)
                    fp.close()
                elif maintype == 'image':
                    fp = open(filepath, 'rb')
                    msgFile = MIMEImage(fp.read(), _subtype=subtype)
                    fp.close()
                elif maintype == 'audio':
                    fp = open(filepath, 'rb')
                    msgFile = MIMEAudio(fp.read(), _subtype=subtype)
                    fp.close()
                else:
                    fp = open(filepath, 'rb')
                    msgFile = MIMEBase(maintype, subtype)
                    msgFile.set_payload(fp.read())
                    fp.close()
                    encoders.encode_base64(msgFile)
                msgFile.replace_header('Content-type','Application/octet-stream;name=%s' % filepath) 
                msgFile.add_header('Content-Disposition', 'attachment',filename = filepath)
                msg.attach(msgFile)
                
            self.login()
            self.server.sendmail(self.user, to, msg.as_string())
            self.close()
            result = True
        except:
            print traceback.format_exc()
        finally:
            return result

if __name__ == '__main__':
    mail = Mail('smtp.2980.com','datang1@2980.com','')
    mails = ['wpsch@qq.com','hellpc@163.com','z7spc@qq.com','380526183@qq.com','1017526594@qq.com','datang1@2980.com','z7spcc@163.com']
    for key in mails:
        print str(mail.send(key, u'测试邮件', u'测试邮件'))
    
    #print str(mail.sendHTMLEmail('meihua_ye@163.com', u'测试邮件','<font style="color:red">测试邮件</font><img src="cid:image1" /><img src="cid:image2" />',['test.jpg','test.jpg']))
    #print str(mail.sendMultiMail('meihua_ye@163.com', u'测试邮件','<font style="color:red">测试邮件</font><img src="cid:image1" /><img src="cid:image2" />',['constant.py','constant.py'],['test.jpg','test.jpg']))
